<template>
  <div class="douyin-video-slider">
    <!-- 加载状态 -->
    <div v-if="isLoadingVideos" class="loading-spinner">
      <div class="spinner"></div>
      <p>加载视频中...</p>
    </div>

    <!-- 错误提示 -->
    <div v-if="loadError && !isLoadingVideos" class="error-message">
      <p>{{ loadError }}</p>
      <button @click="retryLoad">重试</button>
    </div>

    <!-- 加载更多指示器 -->
    <div v-if="isLoadingMore" class="loading-more">
      <div class="spinner small"></div>
    </div>

    <!-- 评论弹窗 - 右侧滑出效果 -->
    <div 
      v-if="showCommentDialog" 
      class="comment-mask"
      @click="closeCommentDialog"
    ></div>
    <div 
      v-if="showCommentDialog" 
      class="comment-container"
      :class="{ 'comment-container-visible': showCommentDialog }"
    >
      <div class="comment-header">
        <h3>评论 ({{ currentComments.length }})</h3>
        <span class="close-icon" @click="closeCommentDialog">×</span>
      </div>
      
      <div class="comment-list">
        <div 
          class="comment-item" 
          v-for="(comment, index) in currentComments" 
          :key="comment.id || index"  
          @dblclick="handleCommentDoubleClick(comment)"
        >
          <div class="comment-avatar" 
              :style="{ 
                backgroundImage: comment.filePath ? `url(${comment.filePath})` : 'url(/default-avatar.png)' 
              }"></div>
          <div class="comment-content">
            <div class="comment-user">{{ comment.userName }}</div>
            <div class="comment-text">{{ comment.content }}</div>
            <div class="comment-footer">
              <!-- <span class="comment-time">{{ formatCommentTime(comment.createTime) }}</span> -->
              <span class="comment-like">❤️ {{ comment.likeCount || 0 }}</span>
            </div>
          </div>
        </div>
        <div v-if="currentComments.length === 0 && !isLoadingComments" class="no-comments">
          还没有评论，快来抢沙发吧~
        </div>
        <div v-if="isLoadingComments" class="loading-comments">
          <div class="spinner small"></div>
        </div>
         
    <!-- 删除确认弹窗 -->
    <div v-if="showDeleteConfirm" class="delete-confirm">
      <p>确定要删除这条评论吗？</p>
      <div class="delete-confirm-buttons">
        <button @click="cancelDelete">取消</button>
        <button @click="confirmDelete">确认删除</button>
      </div>
    </div>
      </div>
      
      <div class="comment-input-area">
        <input 
          type="text" 
          v-model="newCommentContent" 
          placeholder="添加评论..."
          @keyup.enter="submitComment"
        >
        <button @click="submitComment">发送</button>
      </div>
    </div>

    <div
      class="video-container"
      ref="videoContainer"
      :style="{ 
        transform: `translateY(${dragOffset}px)`,
        transition: isDragging ? 'none' : 'transform 0.3s ease',
        width: showCommentDialog ? '60%' : '100%',
        transition: showCommentDialog ? 'width 0.3s ease' : 'none'
      }"
      @mousedown="handleMouseDown"
      @mousemove="handleMouseMove"
      @mouseup="handleMouseUp"
      @mouseleave="handleMouseUp"
      @touchstart="handleTouchStart"
      @touchmove="handleTouchMove"
      @touchend="handleTouchEnd"
    >
      <!-- 视频列表 -->
      <div
        class="video-item"
        v-for="(item, index) in videoList"
        :key="item.id"
      >
        <!-- 视频区域 -->
        <div class="video-wrapper">
          <video
            class="video-player"
            :src="item.videoUrl"
            :autoplay="index === currentIndex"
            loop
            playsinline
            :ref="el => videoPlayers[index] = el"
            @play="onVideoPlay(index)"
            @timeupdate="onTimeUpdate(index)"
            @loadedmetadata="onLoadedMetadata(index)"
            @dblclick="handleDoubleClick(index)"
            @click="handleSingleClick(index)"
          ></video>
          
          <!-- 播放/暂停按钮 -->
          <div 
            class="play-pause-btn" 
            v-if="index === currentIndex && showPlayPauseBtn"
          >
            {{ isPlaying ? '⏸️' : '▶️' }}
          </div>
          
          <!-- 视频进度条 -->
          <div 
            class="video-progress" 
            v-if="index === currentIndex && isProgressBarVisible"
            @mouseenter="keepProgressBarVisible"
            @mouseleave="autoHideProgressBar"
          >
            <div class="progress-background"
              @click.stop="handleProgressClick(index, $event)"
              @touchstart.stop="handleProgressClick(index, $event, true)"
            >
              <div class="progress-buffer" :style="{ width: `${item.bufferProgress}%` }"></div>
              <div class="progress-bar" :style="{ width: `${item.progress}%` }"></div>
            </div>
            <div 
              class="progress-handle"
              :style="{ left: `${item.progress}%` }"
              @mousedown.stop="(e) => handleProgressDragStart(index, e)"
              @touchstart.stop="(e) => handleProgressDragStart(index, e, true)"
            ></div>
          </div>
        </div>
        
        <!-- 底部信息区域 -->
        <div class="video-info">
          <div class="creator-info">
            <div class="avatar" :style="{ backgroundImage: `url(${item.avatar || '/default-avatar.png'})` }"></div>
            <div class="username">{{item.nickname}}</div>
            <button class="follow-btn">关注</button>
          </div>
          
          <div class="title-wrapper">
            <p class="title">{{ item.description }}</p>
          </div>
          
          <div class="interaction">
            <span 
              @click="handleLike(index)" 
              class="like-btn"
            >
              <span :class="['like-icon', item.isLiked ? 'liked' : '', item.isLoading ? 'loading' : '']">♡</span> 
              {{ formatNumber(item.likeCount) }}
            </span>
            <span @click="handleComment(index)" class="comment-btn">
              💬 {{ commentCount}}
            </span>
            <span class="view-count">👁️ {{ formatNumber(item.viewCount) }}</span>
          </div>
        </div>
        
        <!-- 右侧操作区 -->
        <div class="right-action">
          <div 
            class="action-item" 
            @click="handleLike(index)"
          >
            <span :class="['like-icon', item.isLiked ? 'liked' : '', item.isLoading ? 'loading' : '']">♡</span>
            <span class="action-label">{{ formatNumber(item.likeCount) }}</span>
          </div>
          <div class="action-item" @click="handleComment(index)">
            <span>💬</span>
            <span class="action-label">{{ commentCount }}</span>
          </div>
          <div class="action-item">
            <span  @click="handleShare(item.videoUrl)">🔁</span>
            <span class="action-label">链接</span>
          </div>
          <div class="action-item more-btn">
            <span>⋮</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed, watch } from 'vue';
import { useAiMessageStore1 } from '@/stores/recommendStore'
import { message } from 'ant-design-vue'
import { useObtainVideoStore } from '@/stores/obtainVideoStore';
import { useVideoCommentStore } from '@/stores/contentStore';
// import { format } from 'date-fns';

// 视频数据列表
const videoList = ref([]);

// 加载状态管理
const isLoadingVideos = ref(false);
const isLoadingMore = ref(false);
const loadError = ref('');
const hasMore = ref(true);

// 评论相关状态
const commentStore = useVideoCommentStore();
const commentCount = ref(0);
const isLoadingCommentCount = ref(false);
const showCommentDialog = ref(false);
const currentCommentIndex = ref(-1);
const currentComments = ref([]);
const newCommentContent = ref('');
const videoWasPlaying = ref(false);
const isLoadingComments = ref(false);

// 删除评论相关状态
const showDeleteConfirm = ref(false);
const commentToDelete = ref(null);

// 视频播放状态管理
const currentIndex = ref(0);
const videoContainer = ref(null);
const videoPlayers = ref([]);
const isDragging = ref(false);
const isProgressDragging = ref(false);
const startY = ref(0);
const dragOffset = ref(0);
const screenHeight = ref(window.innerHeight);
const isProgressBarVisible = ref(false);
const progressBarTimer = ref(null);
const isPlaying = ref(true);
const showPlayPauseBtn = ref(false);
const playPauseBtnTimer = ref(null);
let clickTimer = null;

// 滚轮节流控制
const isWheelProcessing = ref(false);
const wheelCooldown = 500;

// 计算属性和Store
const baseOffset = computed(() => -currentIndex.value * screenHeight.value);
const recommendStore = useAiMessageStore1();
const obtainVideoStore = useObtainVideoStore();
// // 格式化评论时间
// const formatCommentTime = (time) => {
//   if (!time) return '';
//   const date = new Date(time);
//   return format(date, 'yyyy-MM-dd HH:mm');
// };

// 格式化数字（1k, 1M等）
const formatNumber = (num) => {
  if (num >= 1000000) {
    return (num / 1000000).toFixed(1) + 'M';
  } else if (num >= 1000) {
    return (num / 1000).toFixed(1) + 'k';
  }
  return num;
};

// 评论对话框控制
const handleComment = async (index) => {
  const currentVideo = videoPlayers.value[currentIndex.value];
  if (currentVideo) {
    videoWasPlaying.value = !currentVideo.paused;
  }
  
  currentCommentIndex.value = index;
  const videoId = videoList.value[index].id;
  
  // 加载评论
  try {
    isLoadingComments.value = true;
    const comments = await commentStore.fetchComments(videoId);
    currentComments.value = comments;
  } catch (error) {
    message.error('加载评论失败');
  } finally {
    isLoadingComments.value = false;
  }
  
  showCommentDialog.value = true;
  document.body.style.overflow = 'hidden';
};

// 获取视频评论数量
const fetchVideoCommentCount = async (videoId) => {
  if (!videoId) return 0;
  isLoadingCommentCount.value = true;
  try {
    const count = await commentStore.fetchCommentCount(videoId);
    commentCount.value = count;
    return count;
  } catch (error) {
    console.error('获取评论数量失败:', error);
    return 0;
  } finally {
    isLoadingCommentCount.value = false;
  }
};

// 关闭评论对话框
const closeCommentDialog = () => {
  showCommentDialog.value = false;
  newCommentContent.value = '';
  document.body.style.overflow = '';
  
  const currentVideo = videoPlayers.value[currentIndex.value];
  if (currentVideo && !videoWasPlaying.value) {
    currentVideo.pause();
    isPlaying.value = false;
  }
};

// 处理评论双击事件
const handleCommentDoubleClick = (comment) => {
  // 验证用户是否登录
  const userInfo = JSON.parse(localStorage.getItem("userInfo") || '{}');
  if (!userInfo.id) {
    message.warning('请先登录');
    return;
  }

  // 验证是否是评论作者
  if (comment.userId !== userInfo.id) {
    message.warning('只能删除自己的评论');
    return;
  }

  // 显示删除确认
  commentToDelete.value = comment;
  showDeleteConfirm.value = true;
};

// 取消删除
const cancelDelete = () => {
  showDeleteConfirm.value = false;
  commentToDelete.value = null;
};

// 确认删除
const confirmDelete = async () => {
  if (!commentToDelete.value) return;

  try {
    const userInfo = JSON.parse(localStorage.getItem("userInfo") || '{}');
    const params = {
      commentId: commentToDelete.value.id,
      videoId: videoList.value[currentCommentIndex.value].id,
      userId: userInfo.id
    };

    // 调用删除接口
    const success = await commentStore.deleteComment(params);
    if (success) {
      message.success('评论已删除');
      // 更新评论列表
      currentComments.value = currentComments.value.filter(
        item => item.id !== commentToDelete.value.id
      );
      // 更新评论数量
      const count = await commentStore.fetchCommentCount(params.videoId);
      commentCount.value = count;
      videoList.value[currentCommentIndex.value].commentCount = count;
    }
  } catch (error) {
    message.error('删除失败，请重试');
  } finally {
    showDeleteConfirm.value = false;
    commentToDelete.value = null;
  }
};

// 提交评论
const submitComment = async () => {
  if (!newCommentContent.value.trim() || currentCommentIndex.value === -1) return;
  
  // 获取用户信息
  const userInfo = JSON.parse(localStorage.getItem("userInfo") || '{}');
  
  if (!userInfo.id  || !userInfo.name) {
    message.warning('请先登录');
    return;
  }
  
  const videoId = videoList.value[currentCommentIndex.value].id;
  const commentParams = {
    userId: userInfo.id,
    userName: (userInfo.nickname && userInfo.nickname.trim() !== '') ? userInfo.nickname : userInfo.username,
    videoId,
    content: newCommentContent.value.trim(),
    filePath: userInfo.filePath
  };
  
  try {
    await commentStore.sendComment(commentParams);
    
    // 重新获取评论列表和评论数量
    const [comments, count] = await Promise.all([
      commentStore.fetchComments(videoId),
      commentStore.fetchCommentCount(videoId)
    ]);
    currentComments.value = comments;
    commentCount.value = count;
    videoList.value[currentCommentIndex.value].commentCount = count;
    
    newCommentContent.value = '';
    message.success('评论成功');
  } catch (error) {
    message.error('评论失败，请重试');
  }
};

// 进度条控制
const toggleProgressBar = (index) => {
  if (index !== currentIndex.value) return;
  
  clearProgressBarTimer();
  isProgressBarVisible.value = !isProgressBarVisible.value;
  
  if (isProgressBarVisible.value) {
    progressBarTimer.value = setTimeout(() => {
      isProgressBarVisible.value = false;
    }, 3000);
  }
};

const keepProgressBarVisible = () => {
  if (!isProgressBarVisible.value) return;
  clearProgressBarTimer();
};

const autoHideProgressBar = () => {
  if (!isProgressBarVisible.value || isProgressDragging.value) return;
  progressBarTimer.value = setTimeout(() => {
    isProgressBarVisible.value = false;
  }, 1000);
};

const clearProgressBarTimer = () => {
  if (progressBarTimer.value) {
    clearTimeout(progressBarTimer.value);
    progressBarTimer.value = null;
  }
};

// 播放/暂停控制
const togglePlayPause = (index) => {
  if (index !== currentIndex.value) return;
  
  const video = videoPlayers.value[index];
  if (!video) return;
  
  if (video.paused) {
    video.play().then(() => {
      isPlaying.value = true;
    }).catch(err => {
      console.log('播放失败:', err);
    });
  } else {
    video.pause();
    isPlaying.value = false;
  }
  
  showPlayPauseBtn.value = true;
  resetPlayPauseTimer();
};

const resetPlayPauseTimer = () => {
  if (playPauseBtnTimer.value) {
    clearTimeout(playPauseBtnTimer.value);
  }
  playPauseBtnTimer.value = setTimeout(() => {
    showPlayPauseBtn.value = false;
  }, 2000);
};

// 视频事件处理
const onVideoPlay = (index) => {
  if (index !== currentIndex.value && videoPlayers.value[index]) {
    videoPlayers.value[index].pause();
  }
  if (index === currentIndex.value) {
    isPlaying.value = true;
  }
};

/**
 * 处理分享逻辑
 */
const handleShare = (videoUrl) => {
  if (!videoUrl) return;

  try {
    const shareUrl = videoUrl;
    navigator.clipboard.writeText(shareUrl).then(() => {
      message.success('分享链接已复制');
    }).catch(err => {
      console.error('剪贴板复制失败，使用降级方案', err);
      const tempInput = document.createElement('input');
      tempInput.value = shareUrl;
      document.body.appendChild(tempInput);
      tempInput.select();
      document.execCommand('copy');
      document.body.removeChild(tempInput);
      message.success('分享链接已复制');
    });
  } catch (error) {
    console.error('生成分享链接失败', error);
    message.error('分享链接生成失败，请重试');
  }
};

const onTimeUpdate = (index) => {
  if (index !== currentIndex.value) return;
  
  const video = videoPlayers.value[index];
  if (!video || !video.duration) return;

  const progress = (video.currentTime / video.duration) * 100;
  videoList.value[index].currentTime = video.currentTime;
  videoList.value[index].progress = progress;

  if (video.buffered && video.buffered.length > 0) {
    const bufferedEnd = video.buffered.end(video.buffered.length - 1);
    const bufferProgress = (bufferedEnd / video.duration) * 100;
    videoList.value[index].bufferProgress = bufferProgress;
  }
};

const onLoadedMetadata = (index) => {
  const video = videoPlayers.value[index];
  if (video) {
    videoList.value[index].duration = video.duration;
  }
};

// 点击事件处理
const handleDoubleClick = (index) => {
  if (clickTimer) {
    clearTimeout(clickTimer);
    clickTimer = null;
  }
  toggleProgressBar(index);
};

const handleSingleClick = (index) => {
  if (clickTimer) {
    clearTimeout(clickTimer);
  }
  clickTimer = setTimeout(() => {
    togglePlayPause(index);
    clickTimer = null;
  }, 300);
};

// 加载更多视频
const loadMoreVideos = async () => {
  if (isLoadingMore.value || !hasMore.value) return;
  
  isLoadingMore.value = true;
  
  try {
    const newVideos = await obtainVideoStore.fetchRandomVideos(6);
    
    if (newVideos && newVideos.length > 0) {
      const existingIds = new Set(videoList.value.map(v => v.id));
      const uniqueVideos = newVideos.filter(v => !existingIds.has(v.id));
      
      const videosWithProps = uniqueVideos.map(video => ({
        ...video,
        isLiked: false,  // 初始值设为false，后续会通过fetchCurrentVideoLikeStatus更新
        currentTime: 0,
        duration: 0,
        progress: 0,
        bufferProgress: 0,
        isLoading: false
      }));
      
      videoList.value.push(...videosWithProps);
      hasMore.value = uniqueVideos.length === 4;
    } else {
      hasMore.value = false;
    }
  } catch (err) {
    console.error('加载更多视频失败:', err);
    message.error('加载更多视频失败');
  } finally {
    isLoadingMore.value = false;
  }
};

// 重试加载视频
const retryLoad = async () => {
  await initVideos();
};

// 点赞相关 - 获取点赞数量
const fetchCurrentVideoLikeCount = async (index) => {
  const item = videoList.value[index];
  const parsedUserInfo = JSON.parse(localStorage.getItem("userInfo") || '{}');
  const userId = parsedUserInfo?.id;
  
  if (!userId || !item.id) {
    console.error('用户ID或视频ID不存在，无法获取点赞数');
    return;
  }

  try {
    // 强制从后端获取最新点赞数，不依赖本地缓存
    const count = await recommendStore.getVideoLikeCount(userId, item.id);
    if (count !== null && count !== undefined) {
      item.likeCount = count;
    }
  } catch (error) {
    console.error(`获取视频 ${item.id} 点赞数失败`, error);
  }
};

// 视频切换处理 - 强化状态同步
watch(currentIndex, async (newIndex, oldIndex) => {
  isProgressBarVisible.value = false;
  clearProgressBarTimer();
  
  // 暂停上一个视频
  if (oldIndex !== null && videoPlayers.value[oldIndex]) {
    videoList.value[oldIndex].currentTime = videoPlayers.value[oldIndex].currentTime;
    videoPlayers.value[oldIndex].pause();
  }
  
  // 播放当前视频并强制同步点赞状态和数量
  if (videoPlayers.value[newIndex]) {
    const video = videoPlayers.value[newIndex];
    if (videoList.value[newIndex].currentTime) {
      video.currentTime = videoList.value[newIndex].currentTime;
    }
    video.play().then(() => {
      isPlaying.value = true;
    }).catch(err => {
      console.log('需要用户交互才能播放:', err);
      isPlaying.value = false;
    });
    
    // 先同步点赞状态，再同步数量，确保顺序性
    await fetchCurrentVideoLikeStatus(newIndex);
    await fetchCurrentVideoLikeCount(newIndex);
    
    // 同步评论数量
    const count = await fetchVideoCommentCount(videoList.value[newIndex].id);
    videoList.value[newIndex].commentCount = count;
  }
});

// 监听当前索引，加载更多视频
watch(currentIndex, (newIndex) => {
  const remaining = videoList.value.length - newIndex - 1;
  if (remaining <= 2 && hasMore.value && !isLoadingMore.value) {
    loadMoreVideos();
  }
});

// 获取点赞状态 - 修复核心：强化同步逻辑
const fetchCurrentVideoLikeStatus = async (index) => {
  const item = videoList.value[index];
  const parsedUserInfo = JSON.parse(localStorage.getItem("userInfo") || '{}');
  const userId = parsedUserInfo?.id;
  
  if (!userId || !item.id) {
    console.error('用户ID或视频ID不存在');
    return;
  }

  try {
    // 关键修复1：先清除本地状态，避免使用旧值
    item.isLiked = null; // 临时标记为未初始化状态
    // 关键修复2：强制从后端拉取最新状态，不依赖本地缓存
    const hasLiked = await recommendStore.checkHasLiked(userId, item.id);
    // 确保状态正确更新
    item.isLiked = hasLiked;
    console.log(`视频 ${item.id} 点赞状态同步完成:`, hasLiked);
  } catch (error) {
    console.error(`获取视频 ${item.id} 点赞状态失败`, error);
    // 失败时默认标记为未点赞，避免状态异常
    item.isLiked = false;
  }
};

// 进度条交互
const handleProgressClick = (index, e, isTouch = false) => {
  if (index !== currentIndex.value) return;
  
  const video = videoPlayers.value[index];
  if (!video || !video.duration) return;
  
  const progressBar = e.target.closest('.video-progress');
  if (!progressBar) return;
  
  const rect = progressBar.getBoundingClientRect();
  const x = isTouch ? e.touches[0].clientX : e.clientX;
  const pos = Math.max(0, Math.min(1, (x - rect.left) / rect.width));
  
  video.currentTime = pos * video.duration;
  
  clearProgressBarTimer();
  progressBarTimer.value = setTimeout(() => {
    isProgressBarVisible.value = false;
  }, 3000);
};

const handleProgressDragStart = (index, e, isTouch = false) => {
  if (index !== currentIndex.value) return;
  
  isProgressDragging.value = true;
  isProgressBarVisible.value = true;
  handleProgressDrag(index, e, isTouch);
  
  clearProgressBarTimer();
  
  const moveHandler = (e) => handleProgressDrag(index, e, isTouch);
  const endHandler = () => {
    handleProgressDragEnd(index, videoPlayers.value[index]);
    document.removeEventListener(isTouch ? 'touchmove' : 'mousemove', moveHandler);
    document.removeEventListener(isTouch ? 'touchend' : 'mouseup', endHandler);
    
    progressBarTimer.value = setTimeout(() => {
      isProgressBarVisible.value = false;
    }, 3000);
  };
  
  document.addEventListener(isTouch ? 'touchmove' : 'mousemove', moveHandler);
  document.addEventListener(isTouch ? 'touchend' : 'mouseup', endHandler);
  
  e.stopPropagation();
  if (isTouch) e.preventDefault();
};

const handleProgressDrag = (index, e, isTouch = false) => {
  if (!isProgressDragging.value || index !== currentIndex.value) return;
  
  const video = videoPlayers.value[index];
  if (!video || !video.duration) return;
  
  e.stopPropagation();
  if (isTouch) e.preventDefault();
  
  const progressBar = document.querySelector(`.video-item:nth-child(${index + 1}) .video-progress`);
  if (!progressBar) return;
  
  const rect = progressBar.getBoundingClientRect();
  const x = isTouch ? e.touches[0].clientX : e.clientX;
  const pos = Math.max(0, Math.min(1, (x - rect.left) / rect.width));
  
  videoList.value[index].progress = pos * 100;
};

const handleProgressDragEnd = (index, video) => {
  if (!isProgressDragging.value || !video) return;
  
  isProgressDragging.value = false;
  const pos = videoList.value[index].progress / 100;
  video.currentTime = pos * video.duration;
};

// 滑动切换视频
const handleMouseDown = (e) => {
  if (isProgressDragging.value || showCommentDialog.value) return;
  isDragging.value = true;
  startY.value = e.clientY;
};

const handleTouchStart = (e) => {
  if (isProgressDragging.value || showCommentDialog.value) return;
  isDragging.value = true;
  startY.value = e.touches[0].clientY;
};

const handleMouseMove = (e) => {
  if (isProgressDragging.value || !isDragging.value || showCommentDialog.value) return;
  const delta = e.clientY - startY.value;
  dragOffset.value = baseOffset.value + delta;
};

const handleTouchMove = (e) => {
  if (isProgressDragging.value || !isDragging.value || showCommentDialog.value) return;
  const delta = e.touches[0].clientY - startY.value;
  dragOffset.value = baseOffset.value + delta;
  e.preventDefault();
};

const handleMouseUp = (e) => {
  if (!isDragging.value) return;
  finishDrag(e.clientY - startY.value);
};

const handleTouchEnd = (e) => {
  if (!isDragging.value) return;
  const delta = (e.changedTouches[0].clientY - startY.value);
  finishDrag(delta);
};

const finishDrag = (delta) => {
  isDragging.value = false;
  if (delta < -screenHeight.value / 3 && currentIndex.value < videoList.value.length - 1) {
    currentIndex.value++;
  } else if (delta > screenHeight.value / 3 && currentIndex.value > 0) {
    currentIndex.value--;
  }
  dragOffset.value = baseOffset.value;
};

// 点赞功能 - 修复核心：确保行为与后端状态一致
const handleLike = async (index) => {
  const item = videoList.value[index];
  const parsedUserInfo1 = JSON.parse(localStorage.getItem("userInfo") || '{}');
  const userId = parsedUserInfo1?.id;
  const videoId = item.id;
  
  if (!userId || !videoId) {
    console.error('用户ID或视频ID不存在');
    message.warning('请先登录');
    return;
  }

  // 防止重复点击
  if (item.isLoading) return;

  try {
    item.isLoading = true;
    
    // 关键修复：严格根据后端同步的isLiked状态判断行为
    if (item.isLiked) {
      // 执行取消点赞
      const success = await recommendStore.handleCancelLikeAction(userId, videoId);
      if (success) {
        item.isLiked = false; // 立即更新本地状态
        await fetchCurrentVideoLikeCount(index); // 强制从后端拉取最新数量
      } else {
        // 接口失败时重新同步状态
        await fetchCurrentVideoLikeStatus(index);
        await fetchCurrentVideoLikeCount(index);
      }
    } else {
      // 执行点赞
      const success = await recommendStore.handleLikeAction(userId, videoId);
      if (success) {
        item.isLiked = true; // 立即更新本地状态
        await fetchCurrentVideoLikeCount(index); // 强制从后端拉取最新数量
      } else {
        // 接口失败时重新同步状态
        await fetchCurrentVideoLikeStatus(index);
        await fetchCurrentVideoLikeCount(index);
      }
    }
  } catch (error) {
    console.error('处理点赞状态失败', error);
    message.error('操作失败，请重试');
    // 出错时强制重新同步状态，避免本地状态错乱
    await fetchCurrentVideoLikeStatus(index);
    await fetchCurrentVideoLikeCount(index);
  } finally {
    item.isLoading = false;
  }
};

// 初始化视频数据
const initVideos = async () => {
  isLoadingVideos.value = true;
  loadError.value = '';
  
  try {
    const videos = await obtainVideoStore.fetchRandomVideos(6);
    if (videos && videos.length > 0) {
      videoList.value = videos.map(video => ({
        ...video,
        isLiked: false,  // 初始值设为false，后续会通过fetchCurrentVideoLikeStatus更新
        currentTime: 0,
        duration: 0,
        progress: 0,
        bufferProgress: 0,
        isLoading: false
      }));
      hasMore.value = true;
      
      // 初始化第一个视频的状态
      setTimeout(async () => {
        if (videoPlayers.value[0]) {
          videoPlayers.value[0].play().catch(err => {
            console.log('初始化播放失败:', err);
            isPlaying.value = false;
          });
          // 强制同步第一个视频的点赞状态和数量
          await fetchCurrentVideoLikeStatus(0);
          await fetchCurrentVideoLikeCount(0);
          const count = await fetchVideoCommentCount(videos[0].id);
          videoList.value[0].commentCount = count;
          commentCount.value = count;
        }
      }, 100);
    } else {
      loadError.value = '未获取到视频数据';
      hasMore.value = false;
    }
  } catch (err) {
    loadError.value = '加载视频失败，请稍后重试';
    console.error('视频加载失败:', err);
  } finally {
    isLoadingVideos.value = false;
  }
};

// 生命周期
onMounted(async () => {
  const container = videoContainer.value;
  if (!container) return;

  const resizeHandler = () => {
    screenHeight.value = window.innerHeight;
  };
  window.addEventListener('resize', resizeHandler);

  // 滚轮处理
  const wheelHandler = (e) => {
    if (isWheelProcessing.value || isDragging.value || isProgressDragging.value || showCommentDialog.value) {
      e.preventDefault();
      return;
    }
    isWheelProcessing.value = true;
    
    if (e.deltaY > 0 && currentIndex.value < videoList.value.length - 1) {
      currentIndex.value++;
    } else if (e.deltaY < 0 && currentIndex.value > 0) {
      currentIndex.value--;
    }
    dragOffset.value = baseOffset.value;
    
    setTimeout(() => {
      isWheelProcessing.value = false;
    }, wheelCooldown);
    
    e.preventDefault();
  };
 
  container.addEventListener('wheel', wheelHandler, { passive: false });
  
  // 初始化视频数据
  await initVideos();

  onUnmounted(() => {
    container.removeEventListener('wheel', wheelHandler);
    window.removeEventListener('resize', resizeHandler);
    clearProgressBarTimer();
    if (playPauseBtnTimer.value) {
      clearTimeout(playPauseBtnTimer.value);
    }
    if (clickTimer) {
      clearTimeout(clickTimer);
    }
    document.body.style.overflow = '';
  });
});
</script>

<style scoped>
.douyin-video-slider {
  width: 100%;
  height: 100vh;
  overflow: hidden;
  position: relative;
  background-color: #000;
  display: flex;
}

/* 加载状态样式 */
.loading-spinner {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.8);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  z-index: 9999;
  color: white;
}

.spinner {
  width: 50px;
  height: 50px;
  border: 5px solid rgba(255, 255, 255, 0.3);
  border-top: 5px solid #fff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 16px;
}

.spinner.small {
  width: 30px;
  height: 30px;
  margin-bottom: 0;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 加载更多指示器 */
.loading-more {
  position: fixed;
  bottom: 40px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 50;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 60px;
  height: 60px;
  border-radius: 50%;
  background-color: rgba(0, 0, 0, 0.5);
}

/* 错误提示样式 */
.error-message {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.8);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  z-index: 9999;
  color: white;
}

.error-message button {
  margin-top: 16px;
  padding: 8px 16px;
  background-color: #ff2442;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.video-container {
  width: 100%;
  height: 100%;
  transition: width 0.3s ease;
}

.video-item {
  position: relative;
  width: 100%;
  height: 100vh;
  background-color: #000;
  overflow: hidden;
}

.video-wrapper {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #000;
  overflow: hidden;
}

.video-player {
  width: 100%;
  height: 100%;
  object-fit: contain;
  max-width: 100%;
  max-height: 100%;
  cursor: pointer;
}

/* 播放/暂停按钮 */
.play-pause-btn {
  position: absolute;
  width: 60px;
  height: 60px;
  border-radius: 50%;
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  z-index: 15;
  opacity: 0;
  animation: fadeIn 0.3s ease forwards;
}

@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}

/* 进度条样式 */
.video-progress {
  position: absolute;
  bottom: 80px;
  left: 0;
  width: 100%;
  padding: 0 16px;
  box-sizing: border-box;
  z-index: 20;
  transition: opacity 0.3s ease;
}

.progress-background {
  height: 4px;
  background-color: rgba(255, 255, 255, 0.3);
  border-radius: 2px;
  position: relative;
  cursor: pointer;
}

.progress-buffer {
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  background-color: rgba(255, 255, 255, 0.5);
  border-radius: 2px;
}

.progress-bar {
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  background-color: #ff2442;
  border-radius: 2px;
}

.progress-handle {
  position: absolute;
  top: 50%;
  width: 12px;
  height: 12px;
  background-color: #fff;
  border-radius: 50%;
  transform: translate(-50%, -50%);
  box-shadow: 0 0 8px rgba(0, 0, 0, 0.5);
  cursor: pointer;
  z-index: 10;
  transition: transform 0.2s ease;
}

.progress-handle:hover {
  transform: translate(-50%, -50%) scale(1.2);
}

/* 底部信息样式 */
.video-info {
  position: absolute;
  bottom: 20px;
  left: 20px;
  color: #fff;
  z-index: 10;
  max-width: calc(100% - 120px);
}

.creator-info {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 12px;
}

.avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background-color: #666;
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
}

.username {
  font-size: 16px;
  font-weight: 500;
}

.follow-btn {
  margin-left: 8px;
  padding: 4px 12px;
  background-color: #ff2442;
  color: white;
  border: none;
  border-radius: 20px;
  font-size: 14px;
  cursor: pointer;
}

.title-wrapper {
  margin-bottom: 12px;
}

.title {
  font-size: 18px;
  font-weight: 500;
  margin: 0;
  line-height: 1.4;
}

.interaction {
  display: flex;
  align-items: center;
  gap: 24px;
  font-size: 16px;
}

.like-btn, .comment-btn, .view-count {
  display: flex;
  align-items: center;
  gap: 6px;
  cursor: pointer;
}

/* 右侧操作区 */
.right-action {
  position: absolute;
  right: 12px;
  top: 50%;
  transform: translateY(-50%);
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;
  z-index: 10;
}

.action-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 6px;
  cursor: pointer;
}

.action-item span:first-child {
  width: 44px;
  height: 44px;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: rgba(0, 0, 0, 0.3);
  backdrop-filter: blur(5px);
  font-size: 20px;
}

.action-label {
  font-size: 14px;
  color: #fff;
}

.more-btn {
  margin-top: 10px;
}

/* 点赞按钮样式 */
.like-icon {
  color: #fff;
  font-size: 22px;
}

.like-icon.liked {
  color: #ff2442;
  animation: likeAnimation 0.5s cubic-bezier(0.175, 0.885, 0.32, 1.275);
}

@keyframes likeAnimation {
  0% { transform: scale(1); }
  50% { transform: scale(1.4); }
  100% { transform: scale(1); }
}

/* 点赞加载状态 */
.like-icon.loading {
  animation: spin 1s linear infinite;
}

/* 评论弹窗样式 */
.comment-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 90;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.comment-container {
  position: fixed;
  top: 0;
  right: 0;
  width: 40%;
  height: 100%;
  background-color: #fff;
  z-index: 100;
  transform: translateX(100%);
  transition: transform 0.3s ease;
  display: flex;
  flex-direction: column;
  box-shadow: -5px 0 15px rgba(0, 0, 0, 0.2);
}

.comment-container-visible {
  transform: translateX(0);
}

.comment-container-visible + .comment-mask {
  opacity: 1;
}

.comment-header {
  padding: 16px;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #fff;
  position: sticky;
  top: 0;
  z-index: 10;
}

.comment-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.close-icon {
  font-size: 24px;
  cursor: pointer;
  color: #666;
  width: 36px;
  height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: background-color 0.2s;
}

.close-icon:hover {
  background-color: #f1f1f1;
}

.comment-list {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
  background-color: #f9f9f9;
}

.comment-item {
  display: flex;
  gap: 12px;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #f0f0f0;
}

.comment-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: #ddd;
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
}

.comment-content {
  flex: 1;
}

.comment-user {
  font-weight: 600;
  margin-bottom: 4px;
  font-size: 14px;
  color: #222;
}

.comment-text {
  font-size: 15px;
  margin-bottom: 4px;
  line-height: 1.5;
  color: #333;
}

.comment-footer {
  display: flex;
  gap: 12px;
  font-size: 12px;
  color: #666;
}

.comment-like {
  cursor: pointer;
}

.comment-like:hover {
  color: #ff2442;
}

.no-comments {
  text-align: center;
  padding: 20px;
  color: #666;
  font-size: 14px;
}

.comment-input-area {
  padding: 16px;
  border-top: 1px solid #eee;
  display: flex;
  gap: 12px;
  background-color: #fff;
  position: sticky;
  bottom: 0;
  z-index: 10;
}

.comment-input-area input {
  flex: 1;
  padding: 12px 16px;
  border: 1px solid #ddd;
  border-radius: 24px;
  font-size: 15px;
  outline: none;
  background-color: #f5f5f5;
  color: #333;
}

.comment-input-area input:focus {
  border-color: #ff2442;
  background-color: #fff;
}

.comment-input-area button {
  padding: 12px 20px;
  background-color: #ff2442;
  color: white;
  border: none;
  border-radius: 24px;
  cursor: pointer;
  font-size: 15px;
  white-space: nowrap;
}

/* 隐藏视频默认控制栏 */
video::-webkit-media-controls {
  display: none !important;
}

video {
  -webkit-appearance: none;
  appearance: none;
}

/* 移动端适配 */
@media (max-width: 768px) {
  .comment-container {
    width: 100%;
  }
  
  .video-container {
    width: 100% !important;
    position: absolute;
    z-index: 1;
  }
}

/* 评论加载样式 */
.loading-comments {
  display: flex;
  justify-content: center;
  padding: 20px;
}

/* 删除确认弹窗样式 */
.delete-confirm {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  z-index: 1000;
  width: 300px;
  text-align: center;
}

.delete-confirm p {
  margin: 0 0 16px 0;
  color: #333;
}

.delete-confirm-buttons {
  display: flex;
  justify-content: center;
  gap: 16px;
}

.delete-confirm-buttons button {
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  border: 1px solid #ddd;
}

.delete-confirm-buttons button:first-child {
  background-color: white;
  color: #666;
}

.delete-confirm-buttons button:last-child {
  background-color: #ff2442;
  color: white;
  border-color: #ff2442;
}
</style>
